import Vue from 'vue'
import VueRouter from 'vue-router'

// 确保所有组件文件存在并正确引用
import HomeView from '../views/HomeView.vue' // 确保 HomeView.vue 存在
import LoginView from '../views/LoginView.vue' // 确保 LoginView.vue 存在

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true } // 需要登录
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: () => import('../views/PublicActivitiesView.vue'), // 动态导入
    meta: { requiresAuth: true } // 需要登录
  },
  {
    path: '/public-activities/:id',
    name: 'public-activity-detail',
    component: () => import('../views/PublicActivityDetailView.vue'), // 动态导入
    meta: { requiresAuth: true } // 需要登录
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: () => import('../views/ActivityManagementView.vue'), // 动态导入
    meta: { requiresAuth: true, requiresAdmin: true }, // 需要管理员权限
    beforeEnter: (to, from, next) => {
      const userRole = localStorage.getItem('userRole') || 'student'
      if (userRole === 'admin') {
        next()
      } else {
        alert('无权限访问活动管理页面')
        next('/')
      }
    }
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue') // 动态导入
  },
  {
    path: '/student/:id',
    name: 'student',
    component: () => import('../views/StudentView.vue') // 动态导入
  },
]

const router = new VueRouter({
  routes
})

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  if (requiresAuth && !isAuthenticated) {
    next('/login') // 未登录用户重定向至登录页
  } else {
    next()
  }
})

export default router
